package com.qidian.by.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qidian.by.cms.dto.CategoryDTO;
import com.qidian.by.cms.mapper.ContentCategoryMapper;
import com.qidian.by.cms.service.IContentCategoryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qidian.by.pojo.ContentCategory;
import com.qidian.by.util.exceptions.ServiceExceptionEnum;
import com.qidian.by.util.pojo.EsResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 小可怎么都睡不够
 * @since 2024-05-06
 */
@Service
public class ContentCategoryServiceImpl extends ServiceImpl<ContentCategoryMapper, ContentCategory> implements IContentCategoryService {


    @Override
    public EsResult saveCategory(ContentCategory contentCategory) {
        ContentCategory category = baseMapper.queryCategoryByParentIdAndCatName(contentCategory.getParentId(), contentCategory.getCatName());
        if (category != null) {
            if (category.getStatus() == 99) {
                contentCategory.setCatId(category.getCatId());
                return recover(contentCategory);
            }else{
                return EsResult.error(ServiceExceptionEnum.DEFAULT_FAIL);
            }
        }
        ContentCategory contentCategory1 = baseMapper.queryCategoryByName(contentCategory.getCatName());
        if (contentCategory1 != null) {
            contentCategory.setCatId(contentCategory1.getCatId());
            return recover(contentCategory);
        }
        if (baseMapper.insert(contentCategory) > 0) {
            return EsResult.ok("添加成功", contentCategory);
        } else {

            return EsResult.error(ServiceExceptionEnum.DEFAULT_FAIL);
        }
    }

    @Override
    public EsResult recover(ContentCategory contentCategory) {
        baseMapper.recoverCategory(contentCategory);
        return EsResult.ok();
    }

    @Override
    public EsResult queryAll() {
        QueryWrapper<ContentCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderBy(true, true, "cat_id");
        List<ContentCategory> contentCategories = this.baseMapper.selectList(queryWrapper);
        List<CategoryDTO> cats = assemble(contentCategories);
        return EsResult.ok("查询成功", cats);
    }

    @Override
    public EsResult queryByName(String name) {
        QueryWrapper<ContentCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("cat_name", name);
        List<ContentCategory> contentCategories = this.baseMapper.selectList(queryWrapper);
        List<ContentCategory> res = new ArrayList<>(contentCategories);
        for (ContentCategory contentCategory : contentCategories) {
            List<ContentCategory> parents = findAllAncestors(contentCategory);
            for (ContentCategory item : parents) {
                if (!res.contains(item)) {
                    res.add(item);

                }
            }
        }
        List<CategoryDTO> cats = assemble(res);
        return EsResult.ok("查询成功", cats);
    }

    public List<ContentCategory> findAllAncestors(ContentCategory childCategory) {
        List<ContentCategory> ancestors = new ArrayList<>();
        ContentCategory currentParent = childCategory;

        while (currentParent.getParentId() != 0) {
            ContentCategory parent = this.baseMapper.selectById(currentParent.getParentId());
            if (parent != null) {
                ancestors.add(parent);
                currentParent = parent;
            } else {
                break; // 如果找不到父类别，跳出循环
            }
        }

        return ancestors;
    }

    public List<CategoryDTO> assemble(List<ContentCategory> contentCategories) {
        List<CategoryDTO> rootCats = contentCategories.stream()
                .filter(cc -> cc.getParentId() == 0)
                .map(CategoryDTO::new)
                .collect(Collectors.toList());

        // 对每个根节点递归填充子节点
        for (CategoryDTO rootCat : rootCats) {
            rootCat.assembleChildren(contentCategories);
        }

        return rootCats;
    }
}
